package actions;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import services.TweetService;
import t4p.model.Tweet;
import t4p.model.User;
import t4p.persistence.DaoFactory;

/**
 * Servlet implementation class TweetResponse
 */
@WebServlet("/tweetResponse")
public class TweetResponse extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public TweetResponse() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doAction(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doAction(request, response);
	}

	protected void doAction(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(true);
 		User loggedUser = (User)session.getAttribute("loggedUser");
		
 		String request_ID = request.getParameter("tweetID");
 		Tweet tweetPrevious = null;
 		if (request_ID != null){
 			Long id = Long.valueOf(request_ID);
 			tweetPrevious = DaoFactory.getInstance().getTweetDao().findById(id);
 		}
 		
 		TweetService.addTweet(loggedUser, (String)request.getParameter("txtTwitt"),tweetPrevious);
		
 		response.sendRedirect(response.encodeRedirectURL("/aaarrgh/pages/home.jsp") );
	}

}
